package com.yequan.activemq.topic;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQTextMessage;

import javax.jms.*;

/**
 * @author : Administrator
 * @date : 2020/2/13
 */
public class ActiveMqTopicProducer {

    private static int count = 0;

    public static void testTopicProducer() {
        try {
            //1.创建一个工厂连接对象connectionFactory,需要指定ip和端口
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.157.140:61616");
            //2.使用connectionFactory对象创建一个连接对象connection
            Connection connection = connectionFactory.createConnection();
            //3.启动连接
            connection.start();
            //4.使用connection对象创建session对象
            //参数1:是否开启事务.当该参数为true,第二个参数无效.一半不开启事务
            //参数2:应答模式.自动应答和手动应答模式,一般为自动应答模式
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //5.使用session对象创建destination对象
            Topic topic = session.createTopic("test-topic");
            //6.使用session对象创建生产者对象producer,并制定destination为topic
            MessageProducer producer = session.createProducer(topic);
            //7.创建一个Message对象,这里使用textMessage对象
            TextMessage textMessage = new ActiveMQTextMessage();
            //模拟发送100条消息
            while (count < 100) {
                count++;
                textMessage.setText("Hello ActiveMQ Topic " + count);
                //8.发送消息
                producer.send(textMessage);
                System.out.println("发送的第" + count + "条消息");
                Thread.sleep(1000);
            }
            //9关闭资源
            producer.close();
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        testTopicProducer();
    }

}
